/**
 *       Copyright (c) 2011 Lukas Zaruba
 * 
 *   This file is part of ParPortTester
 *
 *   ParPortTester is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   ParPortTester is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with ParPortTester. If not, see <http://www.gnu.org/licenses/>.
 */


package net.zarubsys.parporttester.core.resp;

import org.eclipse.core.runtime.Assert;

import net.zarubsys.parporttester.io.ParallelPortAccessor;

/**
 * @author  &lt;A HREF=&quot;mailto:lukas.zaruba@gmail.com&quot;&gt;Lukas Zaruba&lt;/A&gt; zarubsys.net
 */
public class InputRunnable implements Runnable {
	
	private static final int READ_DELAY = Integer.parseInt(System.getProperty("readDelay", "5"));
	
	private final int inputAddress;
	private final int pattern;
	private ParallelPortAccessor accessor;
	
	private boolean stopFlag = false;
	private int changesReceived = 0;
	private int timeToFirstResponse = 0;

	
	public InputRunnable(int pattern, int inputAddress) {
		this.pattern = pattern;
		this.inputAddress = inputAddress;
	}
	
	public void resetCount() {
		changesReceived = 0;
	}
	
	public int getChangesReceived() {
		return changesReceived;
	}
	
	public int getTimeToFirstResponse() {
		return timeToFirstResponse;
	}
	
	public void terminate() {
		stopFlag = true;
	}
	
	public void setAccessor(ParallelPortAccessor accessor) {
		this.accessor = accessor;
	}

	@Override
	public void run() {
		Assert.isNotNull(accessor, "Accessor must be set before scheduling this runnable!!!");
		// initialize values
		long timeStamp = System.currentTimeMillis();
		int data = accessor.readOneByte(inputAddress);
		boolean matched = (data & pattern) > 0; 
		boolean innerMatch = false;
		
		changesReceived = 0;
		while (!stopFlag) {
			data = accessor.readOneByte(inputAddress);
			innerMatch = (data & pattern) > 0; 
			if (!matched && innerMatch) {
				if (changesReceived == 0) {
					timeToFirstResponse = (int) (System.currentTimeMillis() - timeStamp);
				}
				timeStamp = System.currentTimeMillis();
				changesReceived++;
			}
			matched = innerMatch;
			
			try {
				Thread.sleep(READ_DELAY);
			} catch (InterruptedException e) {
				// ignore
			}
		}
	}

}
